package constant

import "encoding/json"

// key = Code, string = errMsg
type ErrInfo struct {
	Code int32  `json:"code"`
	Msg  string `json:"msg"`
}

var (
	OK           = ErrInfo{0, "OK"}
	Failed       = ErrInfo{LogicError, "发生错误"}
	ParamsFailed = ErrInfo{ParamsError, "参数错误"}
	ErrServer    = ErrInfo{500, "server error"}
)

const (
	NoError     = 0
	LogicError  = 1
	ParamsError = 2
	LoginFailed = 10000
)

func (e ErrInfo) Error() string {
	return e.Msg
}

func (e *ErrInfo) Codec() int32 {
	return e.Code
}

// 固定返回 http 200
func (e ErrInfo) StatusCode() int {
	return 200
}
func (e ErrInfo) MarshalJSON() ([]byte, error) {
	newMap := map[string]interface{}{
		"code": e.Code,
		"msg":  e.Msg,
	}
	return json.Marshal(newMap)
}

func NewError(code int32, msg string) error {
	return ErrInfo{Code: code, Msg: msg}
}
